import { app, shell, BrowserWindow, ipcMain, screen } from 'electron'
import { join } from 'path'
import pool from './db'
import resp from './resp'
const path = require('path')
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { validateToken, get, post } from './request'
import icon from '../../icon.png?asset'

const unverifiedPort = ['register', 'login']
let calculatorWindow = null;

async function initializeDatabase() {
  try {
    const connection = await pool.getConnection()
    console.log('Connected to MySQL database!')
    connection.release()
  } catch (error) {
    console.error('Error connecting to MySQL:', error)
  }
}

function createWindow() {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize

  const winWidth = 1200
  const winHeight = 800
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: winWidth,
    height: winHeight,
    minWidth: winWidth,
    minHeight: winHeight,
    x: Math.round((width - winWidth) / 2 + 60), // 计算水平居中位置
    y: Math.round((height - winHeight) / 2 + 60), // 计算垂直居中位置
    show: false,
    title: '鲸算',
    autoHideMenuBar: true,
    titleBarStyle: 'hiddenInset',
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
    initializeDatabase()
  })

  // 监听关闭事件
  mainWindow.on('close', (event) => {
    if (!app.isQuitting) {
      event.preventDefault() // 阻止默认关闭行为
      if (calculatorWindow && calculatorWindow.isVisible()) {
        app.calculatorWindowShow = true
      } else if (calculatorWindow && !calculatorWindow.isVisible()) {
        app.calculatorWindowShow = false
      }
      calculatorWindow && calculatorWindow.hide()
      mainWindow.hide()
    }
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // 监听任务栏点击（Windows/Linux）
  app.on('second-instance', () => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.show()
      if (app.calculatorWindowShow) {
        calculatorWindow && calculatorWindow.show()
      }
    }
  })

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow) {
      mainWindow.show()
      if (app.calculatorWindowShow) {
        calculatorWindow && calculatorWindow.show()
      }
    } else {
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    }
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.fluctus')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', async () => {
    let connection
    try {
      // 获取连接
      connection = await pool.getConnection()

      // 执行查询
      const [rows] = await connection.query('SELECT * FROM assets')

    } catch (error) {
      console.error('读取 assets 表时出错:', error)
      throw error
    } finally {
      if (connection) connection.release()
    }
  })

  createWindow()

  // 当应用真的要退出时
  app.on('before-quit', () => {
    app.isQuitting = true
    app.isCalculatorQuitting = true
  })
})

// 监听渲染进程请求打开新窗口
ipcMain.on('open-window', (event, url) => {
  // 如果窗口已存在且未被销毁，则直接聚焦并返回
  if (calculatorWindow && !calculatorWindow.isDestroyed()) {
    calculatorWindow.show()
    calculatorWindow.focus();
    return;
  }

  const parentWindow = BrowserWindow.getFocusedWindow();

  if (!parentWindow) return;

  // 获取父窗口的位置和尺寸
  const [parentX, parentY] = parentWindow.getPosition();
  const [parentWidth, parentHeight] = parentWindow.getSize();

  // 子窗口的尺寸
  const childWidth = 400;
  const childHeight = 540;

  // 计算右下角坐标（考虑窗口边框和任务栏）
  const childX = parentX + parentWidth - childWidth - 10; // 10px 边距
  const childY = parentY + parentHeight - childHeight - 10; // 10px 边距

  calculatorWindow = new BrowserWindow({
    width: childWidth,
    height: childHeight,
    minWidth: childWidth,
    minHeight: childHeight,
    manWidth: childWidth,
    manHeight: childHeight,
    x: childX, // 关键：设置初始位置
    y: childY, // 关键：设置初始位置
    // parent: BrowserWindow.getFocusedWindow(), // 可选：设置为子窗口
    resizable: false,
    minimizable: true,
    maximizable: false,
    modal: false, // 是否为模态窗口
    show: false,
    titleBarStyle: 'hiddenInset',
    backgroundColor: '#1C1C20',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  calculatorWindow.removeMenu()
  calculatorWindow.loadURL(url)
  calculatorWindow.webContents.on('ready-to-show', () => {
    calculatorWindow.show();
    calculatorWindow.setTitle('信用卡&贷款计算器')
  })
  // 当窗口关闭时清除引用
  calculatorWindow.on('closed', () => {
    calculatorWindow = null;
  });
  // 监听关闭事件
  calculatorWindow.on('close', (event) => {
    if (!app.isCalculatorQuitting) {
      event.preventDefault() // 阻止默认关闭行为
      calculatorWindow.hide()
    }
  })
})

ipcMain.handle('get', async (event, ...args) => {
  const tokenInfo = await validateToken(event);

  if (!tokenInfo && !unverifiedPort.includes(args[0].action)) {
    return resp.unauthorized()
  }
  return await get(event, tokenInfo, ...args);
});

ipcMain.handle('post', async (event, ...args) => {
  const tokenInfo = await validateToken(event);
  if (!tokenInfo && !unverifiedPort.includes(args[0].action)) {
    return resp.unauthorized()
  }
  return await post(event, tokenInfo, ...args);
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
// 防止多实例（确保只有一个窗口）
if (!app.requestSingleInstanceLock()) {
  app.quit()
}